<template>

  <div>

    <div style="display: flex; align-items: center; justify-content: space-between">
      <h3>选择考试</h3>
      <el-button size="small" type="warning" icon="el-icon-refresh-left" @click="resetStat">重置表单</el-button>
    </div>
    <el-card>
      <el-tag
        v-for="item in examList"
        :key="item.id"
        style="margin-right: 8px; margin-bottom: 8px"
        closable
        @close="removeExam(item.id)">
        {{ item.title }}
      </el-tag>
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="showExamDialog">添加考试</el-button>
      <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeAll">移除所有</el-button>

    </el-card>

    <h3>统计类型</h3>

    <el-card>
      <el-radio-group v-model="postForm.statType">
        <el-radio label="totalScore">综合统计</el-radio>
        <el-radio label="deptScore">部门统计</el-radio>
        <el-radio label="groupScore">群组统计</el-radio>
        <el-radio label="rangeScore">分数段统计</el-radio>
      </el-radio-group>

      <div v-if="postForm.statType === 'totalScore'" class="desc">
        考试综合统计，包含学员各科成绩、总分、通过情况
      </div>
      <div v-if="postForm.statType === 'deptScore'" class="desc">
        统计部门的考试情况，包括考试人数、通过人数、平均分、通过率等
      </div>
      <div v-if="postForm.statType === 'groupScore'" class="desc">
        统计群组的考试情况，包括考试人数、通过人数、平均分、通过率等
      </div>
      <div v-if="postForm.statType === 'rangeScore'" class="desc">
        统计不同分数段的人员数量、所占比率
        <multi-range-select v-model="postForm.rangeData" :max="totalScore" />
      </div>
    </el-card>

    <h3>人员范围</h3>
    <el-card v-if="postForm.statType === 'totalScore' || postForm.statType === 'rangeScore'">
      <el-radio v-model="postForm.personScope" :label="1">全部参考人员</el-radio>
      <el-radio v-model="postForm.personScope" :label="2">自定义人员范围</el-radio>

      <div v-if="postForm.personScope===1" class="desc">
        根据选定的考试，列出全部参考人员，包含缺考人员
      </div>

      <div v-if="postForm.personScope===2" style="margin-top: 20px">
        <user-range :departs.sync="postForm.deptCodes" :groups.sync="postForm.groupIds" :users.sync="userList"/>
      </div>
    </el-card>

    <el-card v-if="postForm.statType === 'deptScore'">
      <depart-refs v-model="postForm.deptCodes"/>
    </el-card>

    <el-card v-if="postForm.statType === 'groupScore'">
      <group-select v-model="postForm.groupIds" />
    </el-card>


    <div style="margin-top: 20px">
      <el-button type="primary" size="medium" icon="el-icon-magic-stick" @click="generateStat">生成统计</el-button>
    </div>

    <exam-dialog :visible.sync="dialogVisible" @select="examSelected"/>

  </div>

</template>

<script>
import permission from '@/directive/permission/index.js'
import { mapGetters } from 'vuex'
import ExamDialog from '@/components/ExamDialog/index.vue'
import UserRange from '@/components/UserRange/index.vue'
import DepartTreeSelect from '@/components/DepartTreeSelect/index.vue'
import GroupSelect from '@/components/GroupSelect/index.vue'
import MultiRange from '@/components/MultiRange/index.vue'
import MultiRangeSelect from '@/components/MultiRangeSelect/index.vue'

export default {
  components: { MultiRangeSelect, MultiRange, GroupSelect, DepartTreeSelect, UserRange, ExamDialog },
  directives: { permission },
  data() {
    return {
      cacheKey: 'statIndex',
      examList: [],
      userList: [],
      totalScore: 0,
      dialogVisible: false,
      postForm: {
        personScope: 1,
        statType: 'totalScore',
        examIds: [],
        userIds: [],
        deptCodes: [],
        groupIds: [],
        rangeData: ''
      }
    }
  },
  computed: {
    ...mapGetters([
      'siteData'
    ])
  },
  watch: {
    examList: {
      handler(val) {
        const ids = []
        let score = 0
        if (val && val.length > 0) {
          for (let i = 0; i<val.length; i++) {
            ids.push(val[i].id)
            score += val[i].totalScore
          }
        }
        this.totalScore = score
        this.postForm.examIds = ids
      }
    },
    userList: {
      handler(val) {
        const ids = []
        if (val && val.length > 0) {
          for (let i = 0; i<val.length; i++) {
            ids.push(val[i].userId)
          }
        }
        this.postForm.userIds = ids
      }
    }
  },

  created() {
    // 获取缓存
    const cache = localStorage.getItem(this.cacheKey)
    if (cache) {
      const data = JSON.parse(cache)
      if (data.postForm && data.examList && data.userList) {
        this.postForm = data.postForm
        this.examList = data.examList
        this.userList = data.userList
      }
    }
  },
  methods: {

    showExamDialog() {
      this.dialogVisible = true
    },

    examSelected(val) {
      if (!val || val.length === 0) {
        return
      }

      // 加入新的考试
      for (let i = 0; i<val.length; i++) {
        const exam = val[i]
        const contains = this.examList.findIndex(item => item.id === exam.id)
        if (contains === -1) {
          this.examList.push(exam)
        }
      }
    },
    removeExam(id) {
      console.log('移除考试', id)
      for (let i = 0; i<this.examList.length; i++) {
        if (this.examList[i].id === id) {
          this.examList.splice(i, 1)
        }
      }
    },

    // 移除全部考试
    removeAll() {
      this.examList = []
    },

    // 重置
    resetStat() {
      this.examList = []
      this.userList = []
      this.postForm = {
        personScope: 1,
        statType: 'totalScore',
        examIds: [],
        userIds: [],
        deptCodes: [],
        groupIds: []
      }
    },

    // 提交并生成统计
    generateStat() {
      if (!this.postForm.statType) {
        this.$message.warning('请选择一种统计方式！')
        return
      }

      if (!this.postForm.examIds || this.postForm.examIds.length === 0) {
        this.$message.warning('请至少选择一场考试！')
        return
      }

      this.$router.push({ name: 'ExamStatResult', query: { data: JSON.stringify(this.postForm) }})

      // 缓存数据
      const data = {
        postForm: this.postForm,
        userList: this.userList,
        examList: this.examList
      }
      localStorage.setItem(this.cacheKey, JSON.stringify(data))
    }
  }
}
</script>

<style scoped>
.desc{
  margin-top: 20px;
  font-size: 14px;
  color: #888;
}
</style>
